import { RbacMenuType } from '@/data/auth/menu';
import { MenuTypeEnum } from '@/enums/auth';
import { IconOutlinedValueEnum } from '@/enums/icon';
import { useMenus } from '@/hooks/auth/useMenus';
import { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { ProFormGroup } from '@ant-design/pro-form/lib';
import React, { useEffect, useRef, useState } from 'react';

export type UpdateFormProps = {
  onCancel: () => void;
  onSubmit: (values: any) => Promise<void>;
  updateModalVisible: boolean;
  values: Partial<RbacMenuType>;
};

const UpdateModal: React.FC<UpdateFormProps> = (props) => {
  const [updateMenuType, setUpdateMenuType] = useState<any>();
  const formRef = useRef<any>(null);
  const { allMenuValueEnum } = useMenus();

  useEffect(() => {
    setUpdateMenuType(!props.values.parentId ? MenuTypeEnum.Root : MenuTypeEnum.Leaf);
    if (formRef.current && props.updateModalVisible) {
      formRef.current.resetFields();
    }
  }, [props.values, props.updateModalVisible]);

  return (
    <ModalForm
      title="更新"
      width="800px"
      open={props.updateModalVisible}
      onFinish={(values) => {
        return props.onSubmit(values);
      }}
      formRef={formRef}
      onOpenChange={(value) => {
        if (!value) {
          props.onCancel();
        }
      }}
      key={`menu-update-form-${props.values?.id || Math.random()}`}
    >
      <ProFormGroup colProps={{ span: 12 }}>
        <ProFormSelect
          width="md"
          name="parentId"
          label={'父级ID'}
          placeholder={'请输入父级ID'}
          valueEnum={allMenuValueEnum}
          initialValue={props.values.parentId}
          onChange={(value) => {
            if (value) {
              setUpdateMenuType(MenuTypeEnum.Leaf);
            } else {
              setUpdateMenuType(MenuTypeEnum.Root);
            }
          }}
        />
        {updateMenuType === MenuTypeEnum.Root && (
          <ProFormSelect
            rules={[
              {
                required: true,
                message: '图标为必填项',
              },
            ]}
            width="md"
            name="icon"
            label="图标"
            placeholder="请选择图标"
            valueEnum={IconOutlinedValueEnum}
            fieldProps={{
              optionLabelProp: 'label',
            }}
            initialValue={props.values.icon}
          />
        )}
      </ProFormGroup>
      <ProFormGroup colProps={{ span: 12 }}>
        <ProFormText
          rules={[
            {
              required: true,
              message: '菜单名称为必填项',
            },
            {
              pattern: /^[a-zA-Z0-9]+$/,
              message: '只能输入英文字符',
            },
          ]}
          width="md"
          name="name"
          label={'菜单名称'}
          placeholder={'请输入菜单名称'}
          initialValue={props.values.name}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '菜单中文名称为必填项',
            },
            {
              pattern: /^[\u4e00-\u9fa50-9]+$/,
              message: '只能输入中文字符',
            },
          ]}
          width="md"
          name="cnName"
          label={'菜单中文名称'}
          placeholder={'请输入菜单中文名称'}
          initialValue={props.values.cnName}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '路由路径为必填项',
            },
            () => ({
              validator: (_, value) => {
                // 当菜单类型为0(根菜单)时
                if (updateMenuType === MenuTypeEnum.Root) {
                  if (!value.startsWith('/')) {
                    return Promise.reject('根菜单路径必须以/开头');
                  }
                }
                if (updateMenuType === MenuTypeEnum.Leaf) {
                  if (value.startsWith('/')) {
                    return Promise.reject('叶子菜单路径不能以/开头');
                  }
                }
                if (!/^[a-zA-Z0-9/-]*$/.test(value)) {
                  return Promise.reject('根菜单路径只能包含英文字母');
                }
                return Promise.resolve();
              },
            }),
          ]}
          width="md"
          name="path"
          label={'路由路径'}
          placeholder={'请输入路由路径'}
          initialValue={props.values.path}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '排序为必填项',
            },
            {
              pattern: /^\d+$/,
              message: '请输入数字',
            },
          ]}
          width="md"
          name="sort"
          label={'排序'}
          placeholder={'请输入排序号'}
          initialValue={props.values.sort}
        />
      </ProFormGroup>
    </ModalForm>
  );
};

export default UpdateModal;
